package com.pingan.cn.crud;

import io.swagger.annotations.Api;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Api(tags = "通用sql增删改")
@RestController
@RequestMapping("/api/crud")
@CrossOrigin
public class CrudController {

    @Autowired
    private CrudService crudService;

    @PostMapping("/query")
    public ResponseEntity<List<Map<String, Object>>> executeQuery(@RequestBody QueryDto queryDto) {
        try {
            List<Map<String, Object>> result = crudService.executeQuery(queryDto.getSql(), queryDto.getParams());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            // 处理异常，记录日志、返回错误信息给前端等
            System.out.println(e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Collections.singletonList(Collections.singletonMap("error", e.getMessage())));
        }
    }

    @PostMapping("/update")
    public ResponseEntity<Integer> executeUpdate(@RequestBody UpdateDto updateDto) {
        try {
            int result = crudService.executeUpdate(updateDto.getSql(), updateDto.getParams());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            // 处理异常...
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(0);
        }
    }

    // DTO类用于接收前端传入的SQL模板和参数列表
    @Data
    public static class QueryDto {
        private String sql;
        private Object[] params;

        // getter和setter方法...
    }

    @Data
    public static class UpdateDto {
        private String sql;
        private Object[] params;

        // getter和setter方法...
    }


    @PostMapping("/upload2db")
    public ResponseEntity<Integer> uploadExcelFile2db(@RequestParam("file") MultipartFile file, @RequestParam("sql") String sql) {
        try {
            System.out.println("接受的sql： " + sql); // insert into action (id, general_say, soldier_say, title) values (? , ? ,? ,?)
            crudService.uploadExcelFile2db(file, sql);
            return ResponseEntity.ok(0);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(0);
        }
    }
}
